package com.taotao.search.controller;

import java.io.UnsupportedEncodingException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.taotao.common.pojo.EasyUIResult;
import com.taotao.search.pojo.Item;
import com.taotao.service.SearchService;

@Controller
@RequestMapping("search")
public class SearchController {

	@Autowired
	private SearchService searchService;

	private static final Integer ROWS = 32;

	@GetMapping
	public String search(@RequestParam("q") String query,
			@RequestParam(value = "page", defaultValue = "1") Integer pageNum, Model model) {
		
		try {
			query = new String(query.getBytes("iso-8859-1"), "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		EasyUIResult<Item> result = this.searchService.search(query, pageNum, ROWS);
		// 回显查询条件
		model.addAttribute("query", query);
		// 绑定查询结果集
		model.addAttribute("itemList", result.getRows());
		// 页码
		model.addAttribute("page", pageNum);
		// 总页数
		model.addAttribute("pages",
				result.getTotal() % ROWS == 0 ? result.getTotal() / ROWS : result.getTotal() / ROWS + 1);
		return "search";
	}
}
